package com.walk.zworld.ui.activity.my

import android.os.Build
import androidx.annotation.RequiresApi
import com.walk.zworld.R
import com.walk.zworld.db.model.ReadLaterModel
import com.walk.zworld.mvvm.vm.RoomViewModel
import com.walk.zworld.ui.adapter.LaterReadAdapter
import com.walk.zworld.view.MyDialog
import com.walk.zworld.view.SwipeItemLayout
import com.walk.zworld.webView.WebViewActivity
import com.base.lib.base.view.BaseMvvmListActivity

class LaterReadActivity : BaseMvvmListActivity<Any, RoomViewModel, LaterReadAdapter>() {

    override fun onBindAdapter(): Class<LaterReadAdapter> = LaterReadAdapter::class.java

    override fun onBindViewModel(): Class<RoomViewModel>  = RoomViewModel::class.java

    private lateinit var clearDialog: MyDialog

    override fun initView() {
        mRecyclerView.run {
            addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(this@LaterReadActivity))
        }
        mAdapter.run {
            addChildClickViewIds(R.id.rl_read, R.id.btn_delete_read)
            setOnItemChildClickListener { adapter, view, position ->
                val any = data[position]
                when (view.id) {
                    R.id.rl_read -> WebViewActivity.start(
                        this@LaterReadActivity,
                        if (any is ReadLaterModel) any.link else ""
                    )
                    R.id.btn_delete_read -> {
                        mViewModel.removeLater(if (any is ReadLaterModel) any.link else "").observe(this@LaterReadActivity) {
                            adapter.removeAt(position)
                        }
                    }
                }
            }
        }
    }


    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initData() {
        setTop("稍后阅读", "清空")
        setRight("清空") {
            if (!this::clearDialog.isInitialized) {
                clearDialog = MyDialog(this)
                clearDialog.run {
                    setDialogText("清空后无法还原,确认全部删除吗")
                    setClickListener { v ->
                        when (v.id) {
                            R.id.tv_dialog_sure -> {
                                if (clearDialog.isShowing) clearDialog.dismiss()
                                mViewModel.removeAllLater().observe(this@LaterReadActivity) {
                                    mAdapter.setList(mutableListOf())
                                    showNoDataView()
                                }
                            }
                            R.id.tv_dialog_cancle -> if (clearDialog.isShowing) clearDialog.dismiss()
                        }
                    }
                    show()
                }
            } else clearDialog.show()
        }
        onRefreshEvent()
    }
}